package com.bosch.in.rtp1.ept.manager.impl;

import java.sql.Connection;
import java.sql.SQLException;

import com.bosch.in.db.OracleConnectionManager;

/**
 * Class to manage database connection, provide possibility to open and close connection,
 * commit and roll back transaction.
 * @author TPR1HC
 *
 */
class DBConnectionManager {
	
	/**
	 * Database connection instance
	 */
	private Connection con;
	
	/**
	 * Data source object which should be initialized once.
	 */
//	private static DataSource dataSource;
	// Get DataSource    
//	static {         
//		try {
//			Context initContext = new InitialContext();
//			Context envContext  = (Context)initContext.lookup("java:/comp/env");             
//			dataSource = (DataSource)envContext.lookup("jdbc/ept");
//		} catch (NamingException e) {
//			e.printStackTrace();
//		}             
//	}
	
	/**
	 * Constructor which initializes database connection by getting pre-open connection from datasource.
	 * Be default, turn off auto commit feature. 
	 * @throws SQLException
	 */
	public DBConnectionManager() throws SQLException {
//		con = dataSource.getConnection();
//		while (con.isClosed()) {
//			con = dataSource.getConnection();
//		}
//		con.setAutoCommit(false);
		con = OracleConnectionManager.getInstance().getConnection();
		con.setAutoCommit(false);
	}
	
	/**
	 * Get database connection
	 * @return
	 */
	public Connection getConnection() {
		return con;
	}
	
	/**
	 * Commit transaction.
	 * @throws SQLException 
	 */
	public void commit() throws SQLException {
		con.commit();
	}
	
	/**
	 * RollBack transaction.
	 * @throws SQLException
	 */
	public void rollBack() throws SQLException {
		con.rollback();
	}
	
	/**
	 * Close database connection
	 * @throws SQLException
	 */
	public void close() throws SQLException {
		OracleConnectionManager.getInstance().closeConnection(con);
//		if (con != null && !con.isClosed()) {
//			con.close();
//		}
	}
}
